package salary.calculation.config.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liguirong
 */
@Component
@WebFilter(urlPatterns = "/*", filterName = "crossFilter")
public class CrossFilter implements Filter {
    private final int time =  24 * 60 * 60;

    /**
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) {

    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        // 添加参数，允许任意domain访问
        String origin = req.getHeader("origin");
        resp.setHeader("Access-Control-Allow-Origin", origin);
        resp.setHeader("Access-Control-Allow-Headers", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,HEAD");
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie, authorization");
        resp.setHeader("Access-Control-Max-Age", time + "");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(request, resp);
    }

    /**
     * @see Filter#destroy()
     */
    @Override
    public void destroy() {

    }

}
